<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>银行卡号</title>
    <style>
        #cardid{
            width: 280px;
            height: 30px;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <input type="text" id="cardid" placeholder="请输入银行卡号" maxlength="23">

    <script>
        let text = document.querySelector("#cardid");

        function textin() {
            // let str = text.value.replace(/\s/g, ""); // 去掉所有空格
            let str = text.value.replaceAll(" ","");
            str = str.match(/.{1,4}/g)?.join(" ") || ""; // 每 4 个字符加一个空格
            text.value = str;
        }

        text.onblur=textin;
    </script>
</body>
</html>